package com.hui.ruiji.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hui.ruiji.common.CustomException;
import com.hui.ruiji.entity.Category;
import com.hui.ruiji.entity.Dish;
import com.hui.ruiji.entity.Setmeal;
import com.hui.ruiji.mapper.CategoryMapper;
import com.hui.ruiji.service.CategoryService;
import com.hui.ruiji.service.DishService;
import com.hui.ruiji.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {
    @Autowired
    private DishService dishService;

    @Autowired
    private SetmealService setmealService;

    /**
     * 根据ID删除分类，删除前要进行判断
     *
     * @param id
     */
    @Override
    public void remove(Long id) {

        //当前分类是否关联了菜品，如果关联，抛出异常
        LambdaQueryWrapper<Dish> dishQueryWrapper = new LambdaQueryWrapper<>();
        dishQueryWrapper.eq(Dish::getCategoryId, id);
        int count = dishService.count(dishQueryWrapper);
        if (count > 0) {
            //已经关联
            throw new CustomException("当前分类下关联了一个菜品，不能删除");
        }

        //当前分类是否关联了套餐，如果关联，抛出异常
        LambdaQueryWrapper<Setmeal> setmealLambdaQueryWrapper = new LambdaQueryWrapper<>();
        setmealLambdaQueryWrapper.eq(Setmeal::getCategoryId, id);
        int count1 = setmealService.count(setmealLambdaQueryWrapper);
        if (count1 > 0) {
            //已经关联
            throw new CustomException("当前分类下关联了一个套餐 ，不能删除");
        }
        //正常删除
        super.removeById(id);
    }
}
